﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace StateManager
{
    class MultiGameScreen : GenericScreenCode
    {
        // there are a few differences between the single player screen and the multi player screen
        // they are described below

        ContentManager content;
        private Level level;
        int levelNum;


        int players;

        int whoWon;
        int playersPlaying = 0; // this is kept to see how many are playing or are alive
        bool[] totalLanded; // this array holds which landing pads have been claimed

        KeyboardState kb;
        GamePadState[] gb;
        bool[] isAlive; // this array holds which players are alive

        public MultiGameScreen(int num)
        {
            levelNum = 0;
            players = num;
            gb = new GamePadState[players];
            isAlive = new Boolean[players];
            totalLanded = new Boolean[players];
            for (int i = 0; i < isAlive.Length; i++)
            {
                isAlive[i] = true;
                totalLanded[i] = true;
            }

        }

        public override void LoadContent()
        {
         

            content = new ContentManager(SManager.Game.Services, "Content");

            try
            {
                MediaPlayer.IsRepeating = true;
                if (MediaPlayer.GameHasControl)
                    MediaPlayer.Play(content.Load<Song>("sounds/froggertrack"));
                MediaPlayer.Volume = 0.5f;
            }
            catch { }

            loadNextLevel();
            
        }

        public override void UnloadContent()
        {
            MediaPlayer.Stop();
            content.Unload();
        }

        public void loadNextLevel()
        {
            levelNum++;


            for (int i = 0; i < players; i++)
            {
                if (totalLanded[i])
                    playersPlaying++;
                totalLanded[i] = false;
            }

            using (Stream fs = TitleContainer.OpenStream(@"Content/levels/level.txt"))
            {
                level = new MultiPlayerLevel(SManager.Game.Services, fs, SManager.SpriteBatch,
                    SManager.GraphicsDevice.Viewport.Width, SManager.GraphicsDevice.Viewport.Height, levelNum, players, ref isAlive);
            }  
        }

        public override void Update(Microsoft.Xna.Framework.GameTime gameTime, bool setFocus, bool coveredByOtherScreen)
        {

            int allAlive = 0;
            int totalPlaced = 0;
            base.Update(gameTime, setFocus, false);
            kb = Keyboard.GetState();

            for (int i = 0; i < players; i++)
                gb[i] = GamePad.GetState((PlayerIndex)i);

            if (IsActive)
            {
                level.updateLevel(kb, gameTime, gb, ref isAlive, ref totalLanded);

                for (int i = 0; i < players; i++)
                {
                    if (isAlive[i])
                    {
                        allAlive++;
                        whoWon = i + 1;
                    }

                    if (totalLanded[i])
                        totalPlaced++;
                }

                if (allAlive == 1)
                {
                    turnOffRumble();
                    SManager.AddScreen(new GameOverScreen("Player" + whoWon +  "wins"), ControllingPlayer);
                    
                }
                // if the amount of places landed is equal to the amount of players - 1 and the amount of players is two
                else if (totalPlaced == 1 && playersPlaying == 2)
                {
                    turnOffRumble();
                    string thing = String.Empty;

                    for (int i = 0; i < players; i++)
                    {
                        if (isAlive[i] == true)
                            thing += (i.ToString() + " ");
                    }
                    SManager.AddScreen(new GameOverScreen("Player" + whoWon + "Wins"), ControllingPlayer);

                }
                else if ((totalPlaced <= playersPlaying && totalPlaced >= allAlive) || (totalPlaced == playersPlaying - 1)) // if all of the places are filled or the amount of places is greater or equal to the amount of players alive
                {
                    
                    turnOffRumble();
                    string thing = String.Empty;

                    for (int i = 0; i < players; i++)
                    {
                        if (!totalLanded[i])
                            isAlive[i] = false;
                        if (isAlive[i] == true)
                            thing += (i+1.ToString() + " ");
                        isAlive[i] = totalLanded[i];

                        playersPlaying = 0;
                    }
                    SManager.AddScreen(new ContinueScreen("Players" + thing + "go through"), ControllingPlayer);
                    loadNextLevel();
                }
            }
        }

        public static void turnOffRumble()
        {
            for (int i = 0; i < 4; i++)
            {
                GamePad.SetVibration((PlayerIndex)i, 0f, 0f);
            }
        }

        public override void HandleInput(Input input)
        {
            if (input.IsPauseGame(ControllingPlayer))
            {
                MediaPlayer.Volume = 0.1f;
                SManager.AddScreen(new PauseScreen(), ControllingPlayer);
            }
        }

        public override void Draw(Microsoft.Xna.Framework.GameTime gameTime)
        { 
            SManager.GraphicsDevice.Clear(ClearOptions.Target,
                                               Color.CornflowerBlue, 0, 0);

            SpriteBatch sB = SManager.SpriteBatch;

            sB.Begin();

            level.Draw(gameTime, sB);

            sB.End();
        }

        void confirmSelectedEvent(object sender, PlayerEventHandler e)
        {
            LoadScreen.Load(SManager, true, null, new BackgroundScreen(), new TitleScreen());
        }
    }
}
